package li.com.springaidemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.netty.util.internal.StringUtil;
import li.com.springaidemo.mapper.AIMapper;
import li.com.springaidemo.pojo.Persona;
import li.com.springaidemo.service.AIService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.AccessType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AIServiceImpl extends ServiceImpl<AIMapper, Persona> implements AIService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    //    收集用户发送的信息
    @Override
    public List<Message> getMessages(String objectName,String message, List<Message> messages) {
//        用户发送的信息
        Message userMessage = new UserMessage(message);
//        获取储存角色设定
        String description = (String) redisTemplate.opsForValue().get(objectName);
//        判断redis中有没有角色设定数据
        if (StringUtil.isNullOrEmpty(description)){
            //        人物设定
            Persona persona = this.baseMapper.selectOne(new QueryWrapper<Persona>().eq("object_name", objectName));
            description=persona.getDescription()+"返回内容不要输出思考的过程";
//            存入redis
            redisTemplate.opsForValue().set(objectName,persona.getDescription());
        }

        Message systemMessage = new SystemMessage(description);
        // 如果未获取到消息，则创建新的消息并将系统提示和用户输入的消息添加到消息列表中
        if (messages == null){
            messages = new ArrayList<>();
            messages.add(systemMessage);
            messages.add(userMessage);
        } else {
            messages.add(userMessage);
        }
        if (messages.size()>=10){
            messages.remove(1);
            messages.remove(2);
        }
        return messages;
    }
//    收集AI返回的信息，与收集用户发送的信息同时进行
    @Override
    public List<Message> responseMessages(String objectName,ChatResponse chatResponse, List<Message> chatMessage) {
        AssistantMessage output = chatResponse.getResult().getOutput();
        chatMessage.add(output);
        if (chatMessage.size()>=10){
            chatMessage.remove(1);
            chatMessage.remove(2);
        }
        return chatMessage;
    }
}
